//
//  ZKOAuthViewController.swift
//  Weibo
//
//  Created by 郑克哥哥 on 2017/7/25.
//  Copyright © 2017年 郑克哥哥. All rights reserved.
//

import UIKit

import SVProgressHUD

//APPKey:标识应用的唯一ID
let appKey = "1960280711"

//AppSecret:app的秘钥
let AppSecret = "b1460fc2caaa573c3b4c67fca47172bf"

//授权成功回调的地址
let redirect_uri = "http://www.itcast.cn"

//OAuth登录界面
class ZKOAuthViewController: UIViewController {
    
    //懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    
    //自定义控制器视图
    override func loadView() {
        
        webView.delegate = self
        
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        setupNavUI()
        
        loadLogin()
    }

    private func setupNavUI(){
        
        //设置导航栏左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelButton))
        //设置导航栏右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autuFillButton))
        
        //设置导航栏title
        navigationItem.title = "微博登录"
        
    }
    
    
    //MARK: -------导航栏按钮点击事件-------
    @objc private func cancelButton(){
        
        self.dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autuFillButton(){
        
        
        print("自动填充")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '18213369790';document.getElementById('passwd').value = 'zhengke19951023';document.getElementById('passwd').focus()")
    }
    
    //加载第三方登录
    func loadLogin(){
        
        //请求地址
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)"
        
        let url = URL(string: urlStr)
        webView.loadRequest(URLRequest(url: url!))
        
        
    }
    
//    //通过授权码获取令牌(accessToken)
//    func requestAccessToken(code:String) {
//        
//        NetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//            
//            if error != nil{
//                
//                print("error: \(error!)")
//                return
//            }
//            
//            let dict = response as! [String:Any]
//            //字典转模型
//            let userAccount = UserAccountModel(dic: dict)
//            
//            //获取用户信息
//            self.requestUserInfo(userAccount: userAccount)
//            
//        }
//        
//        
//    }
//    
//    //获取用户信息
//    private func requestUserInfo(userAccount:UserAccountModel){
//        
//        let token = userAccount.access_token!
//        let uid = userAccount.uid
//        NetworkTools.sharedTools.requestUserInfo(access_token:token , uid: uid) { (response, error) in
//            
//            if error != nil{
//                
//                print("error: \(error!)")
//                return
//            }
//            
//            //转成对应的字典
//            let dic = response as! [String:Any]
//            //给对象属性赋值
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            
//            print(userAccount.name)
//            
//            //登录成功
//            //保存用户对象
//            userAccount.saveUserAccount()
//        }
//        
//        
//    }
    


}

//MARK: -------webView的代理方法-------
extension ZKOAuthViewController:UIWebViewDelegate{
    
    //将要加载网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        //print(request.url?.absoluteString)
        //表示是以授权回调地址开头
        if request.url?.absoluteString.hasPrefix(redirect_uri) == true{
            
            //query:表示url" ? "后面的参数
            if let query = request.url?.query, query.hasPrefix("code="){
                
                //获取授权码
                let code = query.substring(from: "code=".endIndex)
                
                //通过code授权码获取AccessToken
//                requestAccessToken(code: code)
                ZKUserAccount.sharedViewModel.requestAccessToken(code: code,callBack: {(isSuccess:Bool) in
                
                    if isSuccess{
                        
                        //登录成功之后注意要dismiss上一个控制器
                        print("登录成功")
                        self.dismiss(animated: false, completion: { 
                            //进入首页,切换根视图控制器
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootViewController), object: self)
                        })
                        
                       
                    }else{
                        
                        print("登录失败")
                    }
                
                
                })
                
            }else{
                
                //取消授权,并dismiss
                self.dismiss(animated: true, completion: nil)
                
                
                
            }
            
            //不加载回调页面
            return false
        }
        
        //true表示加载此次请求地址
        return true
    }
    
    //开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        //执行等待指示器
        SVProgressHUD.show()
    }
    
    //完成加载
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //加载异常
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        SVProgressHUD.dismiss()
    }
}



    
    
    
    
